{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "c705573a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "1\n",
      "2\n",
      "2\n",
      "3\n",
      "3\n",
      "4\n",
      "4\n",
      "5\n",
      "5\n",
      "6\n",
      "1\n",
      "2\n",
      "1\n",
      "3\n",
      "2\n",
      "4\n",
      "3\n",
      "5\n",
      "4\n",
      "6\n",
      "5\n",
      "7\n",
      "2\n",
      "3\n",
      "1\n",
      "4\n",
      "2\n",
      "5\n",
      "3\n",
      "6\n",
      "4\n",
      "7\n",
      "5\n",
      "8\n",
      "3\n",
      "4\n",
      "1\n",
      "5\n",
      "2\n",
      "6\n",
      "3\n",
      "7\n",
      "4\n",
      "8\n",
      "5\n",
      "9\n",
      "4\n",
      "5\n",
      "1\n",
      "6\n",
      "2\n",
      "7\n",
      "3\n",
      "8\n",
      "4\n",
      "9\n",
      "5\n",
      "10\n",
      "5\n",
      "done looping\n"
     ]
    }
   ],
   "source": [
    "for i in [1, 2, 3, 4, 5]:\n",
    "    print(i)                    # first line in \"for i\" block\n",
    "    for j in [1, 2, 3, 4, 5]:\n",
    "        print(j)                # first line in \"for j\" block\n",
    "        print(i + j)            # last line in \"for j\" block\n",
    "    print(i)                    # last line in \"for i\" block\n",
    "print(\"done looping\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "83dd29d6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "re.compile(r'[0-9]+', re.IGNORECASE|re.UNICODE)"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import re\n",
    "my_regex = re.compile(\"[0-9]+\", re.I)\n",
    "my_regex"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "be89827a",
   "metadata": {},
   "source": [
    "## Функция - правило, принимающее ноль или несколько аргументов на входе и возвращающее соответствующий результат на выходе "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "c24710ff",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello\n",
      "my default message\n"
     ]
    }
   ],
   "source": [
    "def double(x):\n",
    "    \"\"\"\n",
    "    This is where you put an optional docstring that explains what the\n",
    "    function does. For example, this function multiplies its input by 2.\n",
    "    \"\"\"\n",
    "    return x * 2\n",
    "\n",
    "def apply_to_one(f):\n",
    "    \"\"\"Calls the function f with 1 as its argument\"\"\"\n",
    "    return f(1)\n",
    "\n",
    "my_double = double             # refers to the previously defined function\n",
    "x = apply_to_one(my_double)    # equals 2\n",
    "\n",
    "\n",
    "assert x == 2\n",
    "\n",
    "y = apply_to_one(lambda x: x + 4)      # equals 5\n",
    "\n",
    "\n",
    "assert y == 5\n",
    "\n",
    "another_double = lambda x: 2 * x       # Don't do this\n",
    "\n",
    "def another_double(x):\n",
    "    \"\"\"Do this instead\"\"\"\n",
    "    return 2 * x\n",
    "\n",
    "def my_print(message = \"my default message\"):\n",
    "    print(message)\n",
    "\n",
    "my_print(\"hello\")   # prints 'hello'\n",
    "my_print()          # prints 'my default message'\n",
    "\n",
    "def full_name(first = \"What's-his-name\", last = \"Something\"):\n",
    "    return first + \" \" + last\n",
    "\n",
    "full_name(\"Joel\", \"Grus\")     # \"Joel Grus\"\n",
    "full_name(\"Joel\")             # \"Joel Something\"\n",
    "full_name(last=\"Grus\")        # \"What's-his-name Grus\"\n",
    "\n",
    "\n",
    "assert full_name(\"Joel\", \"Grus\")     == \"Joel Grus\"\n",
    "assert full_name(\"Joel\")             == \"Joel Something\"\n",
    "assert full_name(last=\"Grus\")        == \"What's-his-name Grus\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a0928d8a",
   "metadata": {},
   "source": [
    "## Строки - последовательность символов"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "85aad1aa",
   "metadata": {},
   "outputs": [],
   "source": [
    "ingle_quoted_string = 'data science'\n",
    "double_quoted_string = \"data science\"\n",
    "\n",
    "tab_string = \"\\t\"       # represents the tab character\n",
    "len(tab_string)         # is 1\n",
    "\n",
    "\n",
    "assert len(tab_string) == 1\n",
    "\n",
    "not_tab_string = r\"\\t\"  # represents the characters '\\' and 't'\n",
    "len(not_tab_string)     # is 2\n",
    "\n",
    "\n",
    "assert len(not_tab_string) == 2\n",
    "\n",
    "multi_line_string = \"\"\"This is the first line.\n",
    "and this is the second line\n",
    "and this is the third line\"\"\"\n",
    "\n",
    "first_name = \"Joel\"\n",
    "last_name = \"Grus\"\n",
    "\n",
    "full_name1 = first_name + \" \" + last_name             # string addition\n",
    "full_name2 = \"{0} {1}\".format(first_name, last_name)  # string.format\n",
    "\n",
    "full_name3 = f\"{first_name} {last_name}\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1f3982d6",
   "metadata": {},
   "source": [
    "## Исключения"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "709bb90e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cannot divide by zero\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    print(0 / 0)\n",
    "except ZeroDivisionError:\n",
    "    print(\"cannot divide by zero\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dab8f68e",
   "metadata": {},
   "source": [
    "## Списки - упорядоченная совокупность (или коллекция), похожая на массив в других языках, но с дополнительным функционалом"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "8f42fd61",
   "metadata": {},
   "outputs": [],
   "source": [
    "integer_list = [1, 2, 3]\n",
    "heterogeneous_list = [\"string\", 0.1, True]\n",
    "list_of_lists = [integer_list, heterogeneous_list, []]\n",
    "\n",
    "list_length = len(integer_list)     # equals 3\n",
    "list_sum    = sum(integer_list)     # equals 6\n",
    "\n",
    "\n",
    "assert list_length == 3\n",
    "assert list_sum == 6\n",
    "\n",
    "x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
    "\n",
    "zero = x[0]          # equals 0, lists are 0-indexed\n",
    "one = x[1]           # equals 1\n",
    "nine = x[-1]         # equals 9, 'Pythonic' for last element\n",
    "eight = x[-2]        # equals 8, 'Pythonic' for next-to-last element\n",
    "x[0] = -1            # now x is [-1, 1, 2, 3, ..., 9]\n",
    "\n",
    "\n",
    "assert x == [-1, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
    "\n",
    "first_three = x[:3]                 # [-1, 1, 2]\n",
    "three_to_end = x[3:]                # [3, 4, ..., 9]\n",
    "one_to_four = x[1:5]                # [1, 2, 3, 4]\n",
    "last_three = x[-3:]                 # [7, 8, 9]\n",
    "without_first_and_last = x[1:-1]    # [1, 2, ..., 8]\n",
    "copy_of_x = x[:]                    # [-1, 1, 2, ..., 9]\n",
    "\n",
    "every_third = x[::3]                 # [-1, 3, 6, 9]\n",
    "five_to_three = x[5:2:-1]            # [5, 4, 3]\n",
    "\n",
    "\n",
    "assert every_third == [-1, 3, 6, 9]\n",
    "assert five_to_three == [5, 4, 3]\n",
    "\n",
    "1 in [1, 2, 3]    # True\n",
    "0 in [1, 2, 3]    # False\n",
    "\n",
    "x = [1, 2, 3]\n",
    "x.extend([4, 5, 6])     # x is now [1, 2, 3, 4, 5, 6]\n",
    "\n",
    "\n",
    "assert x == [1, 2, 3, 4, 5, 6]\n",
    "\n",
    "x = [1, 2, 3]\n",
    "y = x + [4, 5, 6]       # y is [1, 2, 3, 4, 5, 6]; x is unchanged\n",
    "\n",
    "\n",
    "assert x == [1, 2, 3]\n",
    "assert y == [1, 2, 3, 4, 5, 6]\n",
    "\n",
    "x = [1, 2, 3]\n",
    "x.append(0)      # x is now [1, 2, 3, 0]\n",
    "y = x[-1]        # equals 0\n",
    "z = len(x)       # equals 4\n",
    "\n",
    "\n",
    "assert x == [1, 2, 3, 0]\n",
    "assert y == 0\n",
    "assert z == 4\n",
    "\n",
    "x, y = [1, 2]    # now x is 1, y is 2\n",
    "\n",
    "\n",
    "assert x == 1\n",
    "assert y == 2\n",
    "\n",
    "_, y = [1, 2]    # now y == 2, didn't care about the first element\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2e5e8733",
   "metadata": {},
   "source": [
    "## Кортежи - то же, что и список, однако кортеж имеет статические характеристики. Списки могут быть изменены, а кортежи нет. Кортеж быстрее списка и обозначается круглыми скобками "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "5b8603fd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cannot modify a tuple\n"
     ]
    }
   ],
   "source": [
    "my_list = [1, 2]\n",
    "my_tuple = (1, 2)\n",
    "other_tuple = 3, 4\n",
    "my_list[1] = 3      # my_list is now [1, 3]\n",
    "\n",
    "try:\n",
    "    my_tuple[1] = 3\n",
    "except TypeError:\n",
    "    print(\"cannot modify a tuple\")\n",
    "\n",
    "def sum_and_product(x, y):\n",
    "    return (x + y), (x * y)\n",
    "\n",
    "sp = sum_and_product(2, 3)     # sp is (5, 6)\n",
    "s, p = sum_and_product(5, 10)  # s is 15, p is 50\n",
    "\n",
    "x, y = 1, 2     # now x is 1, y is 2\n",
    "x, y = y, x     # Pythonic way to swap variables; now x is 2, y is 1\n",
    "\n",
    "\n",
    "assert x == 2\n",
    "assert y == 1"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "421e4ce1",
   "metadata": {},
   "source": [
    "## Словарь - фундаментальная структура данных. Значения ассоциированы с ключами, что позволяет быстро извлекать значение "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "6f4d9d9d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "no grade for Kate!\n"
     ]
    }
   ],
   "source": [
    "empty_dict = {}                     # Pythonic\n",
    "empty_dict2 = dict()                # less Pythonic\n",
    "grades = {\"Joel\": 80, \"Tim\": 95}    # dictionary literal\n",
    "\n",
    "joels_grade = grades[\"Joel\"]        # equals 80\n",
    "\n",
    "\n",
    "assert joels_grade == 80\n",
    "\n",
    "try:\n",
    "    kates_grade = grades[\"Kate\"]\n",
    "except KeyError:\n",
    "    print(\"no grade for Kate!\")\n",
    "\n",
    "joel_has_grade = \"Joel\" in grades     # True\n",
    "kate_has_grade = \"Kate\" in grades     # False\n",
    "\n",
    "\n",
    "assert joel_has_grade\n",
    "assert not kate_has_grade\n",
    "\n",
    "joels_grade = grades.get(\"Joel\", 0)   # equals 80\n",
    "kates_grade = grades.get(\"Kate\", 0)   # equals 0\n",
    "no_ones_grade = grades.get(\"No One\")  # default default is None\n",
    "\n",
    "\n",
    "assert joels_grade == 80\n",
    "assert kates_grade == 0\n",
    "assert no_ones_grade is None\n",
    "\n",
    "grades[\"Tim\"] = 99                    # replaces the old value\n",
    "grades[\"Kate\"] = 100                  # adds a third entry\n",
    "num_students = len(grades)            # equals 3\n",
    "\n",
    "\n",
    "assert num_students == 3\n",
    "\n",
    "tweet = {\n",
    "    \"user\" : \"joelgrus\",\n",
    "    \"text\" : \"Data Science is Awesome\",\n",
    "    \"retweet_count\" : 100,\n",
    "    \"hashtags\" : [\"#data\", \"#science\", \"#datascience\", \"#awesome\", \"#yolo\"]\n",
    "}\n",
    "\n",
    "tweet_keys   = tweet.keys()     # iterable for the keys\n",
    "tweet_values = tweet.values()   # iterable for the values\n",
    "tweet_items  = tweet.items()    # iterable for the (key, value) tuples\n",
    "\n",
    "\"user\" in tweet_keys            # True, but not Pythonic\n",
    "\"user\" in tweet                 # Pythonic way of checking for keys\n",
    "\"joelgrus\" in tweet_values      # True (slow but the only way to check)\n",
    "\n",
    "\n",
    "assert \"user\" in tweet_keys\n",
    "assert \"user\" in tweet\n",
    "assert \"joelgrus\" in tweet_values\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0fcd6a36",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
